package com.youmu.sichuansfc.util;


import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 *  Cookie 操作类
 * @author WYZ
 * @create 2018-02-23 10:53
 * @desc
 **/
public  class CookieUtil {


    private Logger logger = Logger.getLogger(this.getClass());
    private HttpServletRequest request;
    public CookieUtil(HttpServletRequest request){
        this.request = request;
    }

    /**
     *  根据名字获取cookie中的值
     * @param name
     * @return
     */
    public String getCookieByName(String name){
        if (request == null || !StringUtils.isNotEmpty(name)){
            return  null;
        }

        String value = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0 ) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    value = cookie.getValue();
                    break;
                }
            }
        }
        logger.info("从cookie 中取 "+name+" = "+ value);
        //FIXME
        if(!StringUtils.isNotEmpty(value)){
            value = request.getHeader(name);
            logger.info("header 中取 "+name+" = "+ value);
        }
        return  value;
    }
}
